using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace Imagination.Display
{
    /*  ScreenManager manages a collection of Screens   */

    public class ScreenManager : DrawableGameComponent
    {
        private Stack<Screen> activeScreens;

        public Stack<Screen> ActiveScreens
        {
            get { return activeScreens; }
        }
	
        public ScreenManager(Game game) : base(game)
        {
            activeScreens = new Stack<Screen>();
        }

        private void ScreenUpdate(Predicate<Screen> ignore, Predicate<Screen> isBlocking, Action<Screen> doWork)
        {
            List<Screen> screens = new List<Screen>();
            foreach (Screen screen in activeScreens)
            {
                if (screen.IsActive && !ignore(screen))
                {
                    screens.Add(screen);
                    if (isBlocking(screen))
                        break;
                }
            }
            for (int i = screens.Count - 1; i >= 0; i--)
            {
                doWork(screens[i]);
            }
        }
        public override void Update(GameTime gameTime)
        {
            ScreenUpdate(
                delegate(Screen screen) { return !screen.Enabled; }, 
                delegate(Screen screen) { return screen.BlocksUpdate; },
                delegate(Screen screen) { screen.Update(gameTime); }
                );
        }

        public override void Draw(GameTime gameTime)
        {
            ScreenUpdate(
                delegate(Screen screen) { return !screen.Visible; },
                delegate(Screen screen) { return screen.BlocksDraw; },
                delegate(Screen screen) { screen.Draw(gameTime); }
                );
        }

        public override string ToString()
        {
            return String.Format("ScreenManager: {0} screens, viewport={1}x{2}", activeScreens.Count,
                GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
        }
    }
}
